using System;
using System.Collections.Generic;
using System.Linq;

namespace LambdaGp.Core
{
    public static class ExtensionMethods
    {
        public static TItem GetRandomItem<TItem>(this List<TItem> list)
        {
            int pos = ThreadSafeRandom.Random.Next(list.Count);
            return list[pos];
        }

        public static void Randomize<TItem>(this List<TItem> list)
        {
            for (int i = 0; i < list.Count; i++)
            {
                int pos = ThreadSafeRandom.Random.Next(list.Count);
                TItem temp = list[pos];
                list[pos] = list[i];
                list[i] = temp;
            }
        }

        public static TOperator SetCompactCode<TOperator>(this TOperator @operator, string compactCode) where TOperator : Operator
        {
            @operator.CompactCode = compactCode;
            return @operator;
        }        
        
        public static void ForEach<TItem>(this IEnumerable<TItem> enumerable, Action<TItem> action)
        {
            foreach (TItem item in enumerable)
            {
                action(item);
            }
        }

        public static TItem BottomItem<TItem>(this IEnumerable<TItem> enumerable, Func<TItem, IComparable> compare)
        {
            TItem bestSoFar = enumerable.First();
            enumerable.ForEach(item =>
            {
                if (compare(item).CompareTo(compare(bestSoFar)) < 0)
                {
                    bestSoFar = item;
                }
            });
            return bestSoFar;
        }

        public static TItem TopItem<TItem>(this IEnumerable<TItem> enumerable, Func<TItem, IComparable> compare)
        {
            TItem bestSoFar = enumerable.First();
            enumerable.ForEach(item =>
            {
                if (compare(item).CompareTo(compare(bestSoFar)) > 0)
                {
                    bestSoFar = item;
                }
            });
            return bestSoFar;
        }
    }
}
